<template>
  <div class="login-container">
    <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef" label-width="80px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="loginForm.username" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="loginForm.password" type="password" autocomplete="off" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleLogin">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import axios from "axios";
import { ElMessage } from "element-plus";

export default {
  data() {
    return {
      loginForm: {
        username: "",
        password: "",
      },
      loginRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    async handleLogin() {
      this.$refs.loginFormRef.validate(async (valid) => {
        if (valid) {
          try {
            const res = await axios.post("/api/wu_vue_2_test/User/validate", this.loginForm);
            if (res.data.code === 200) {
              // 登录成功，跳转到主页或其他页面
              ElMessage({
                message: "登录成功",
                type: "success",
              });
              // 这里可以添加跳转到主页的逻辑，例如使用路由跳转
              if (res.data.data.user_permission === "customer") {
                // 客户页面
                this.$router.push("/patient");
              }else if (res.data.data.user_permission === "escort") {
                // 陪诊员页面
                this.$router.push("/escort");
              }else if (res.data.data.user_permission === "root") {
                // 管理员页面
                this.$router.push("/serviceRecord");
              }
            } else {
              ElMessage({
                message: res.data.msg,
                type: "error",
              });
            }
          } catch (error) {
            console.error("登录失败:", error);
            ElMessage({
              message: "登录失败，请稍后重试",
              type: "error",
            });
          }
        } else {
          console.log("表单验证不通过");
          return false;
        }
      });
    },
  },
};
</script>

<style scoped>
.login-container {
  width: 300px;
  margin: 100px auto;
}
</style>